import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:intl/intl.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:azring/core/config/api_config.dart';
import 'package:azring/core/controllers/auth_controller.dart';
import 'package:azring/services/device_sn_manager.dart';
import 'package:azring/models/group_interaction_models.dart';
import 'group_detail_state.dart';

/// 群组详情页控制器
class GroupDetailLogic extends GetxController {
  final GroupDetailState state = GroupDetailState();

 

  @override
  void onInit() {
    super.onInit();
    
    // 获取传递的参数
    final args = Get.arguments as Map<String, dynamic>?;
    if (args != null) {
      state.groupId.value = args['groupId'] ?? 0;
      state.groupName.value = args['groupName'] ?? '';
      state.groupCode.value = args['groupCode'] ?? '';
    }
    
    // 设置当前日期
    state.currentDate.value = DateFormat('yyyy/MM/dd').format(DateTime.now());
    
    // 加载数据
    loadGroupDetail();
    loadInteractions();
  }

  /// 加载群组详情
  Future<void> loadGroupDetail() async {
    try {
      state.isLoading.value = true;
      
      // 根据选中的数据类型调用不同的API
      dynamic response;
      switch (state.selectedDataType.value) {
        case 0: // 身体活力
          response = await DefaultApi().queryGroupPhysicalVitalityGet(
            groupId: state.groupId.value,
            isShowLoading: false,
          );
          break;
        case 1: // 睡眠
          response = await DefaultApi().queryGroupSleepGet(
            groupId: state.groupId.value,
            isShowLoading: false,
          );
          break;
        case 2: // 能量平衡
          response = await DefaultApi().queryGroupEnergyBalanceGet(
            groupId: state.groupId.value,
            isShowLoading: false,
          );
          break;
      }
      
      if (response != null && response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        state.memberList.value = data
            .map((item) => GroupMemberData.fromJson(item))
            .toList();
      }
    } catch (e) {
      print('加载群组详情失败: $e');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 加载互动墙
  Future<void> loadInteractions() async {
    try {
      state.isLoadingInteractions.value = true;
      
      // 根据筛选类型决定是否传递 dailyValue
      final dailyValue = state.isShowingToday.value 
          ? state.currentDate.value.replaceAll('/', '-')
          : null;
      
      final response = await DefaultApi().queryShareListGet(
        groupId: state.groupId.value,
        dailyValue: dailyValue,
        isShowLoading: false,
      );
      
      if (response != null && response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        state.interactionList.value = data
            .map((item) => GroupInteraction.fromJson(item))
            .toList();
      }
    } catch (e) {
      print('加载互动墙失败: $e');
    } finally {
      state.isLoadingInteractions.value = false;
    }
  }

  /// 切换数据类型
  void switchDataType(int type) {
    state.selectedDataType.value = type;
    loadGroupDetail();
  }

  /// 切换互动墙筛选类型（今日/全部）
  void toggleInteractionFilter() {
    state.isShowingToday.value = !state.isShowingToday.value;
    state.isAllExpanded.value = false; // 切换时重置展开状态
    loadInteractions();
  }

  /// 切换全部模式下的展开/折叠
  void toggleAllExpanded() {
    state.isAllExpanded.value = !state.isAllExpanded.value;
  }

  /// 获取显示的互动列表（根据筛选和展开状态）
  List<GroupInteraction> get displayedInteractions {
    if (state.isShowingToday.value) {
      // 今日模式：显示全部
      return state.interactionList;
    } else {
      // 全部模式：默认显示5条，展开后显示全部
      if (state.isAllExpanded.value) {
        return state.interactionList;
      } else {
        return state.interactionList.take(5).toList();
      }
    }
  }

  /// 是否显示"查看更多"按钮
  bool get shouldShowMoreButton {
    return !state.isShowingToday.value && 
           state.interactionList.length > 5 && 
           !state.isAllExpanded.value;
  }

  /// 是否显示"收起"按钮
  bool get shouldShowCollapseButton {
    return !state.isShowingToday.value && 
           state.interactionList.length > 5 && 
           state.isAllExpanded.value;
  }

  /// 点赞/取消点赞
  Future<void> likeInteraction(int index) async {
    try {
      final item = state.interactionList[index];
      final currentUserId = AuthController.to.user?.userId;
      
      if (currentUserId == null) {
        Toast.show('请先登录');
        return;
      }
      
      // 检查是否已点赞
      final myThumb = item.getThumbBy(currentUserId);
      
      if (myThumb != null) {
        // 已点赞，取消点赞
        final response = await DefaultApi().shareDeleteThumbDel(
          thumbId: myThumb.thumbId,
          isShowLoading: false,
        );
        
        if (response != null && response['code'] == 200) {
          // 重新加载互动墙以获取最新数据
          await loadInteractions();
        }
      } else {
        // 未点赞，添加点赞
        final response = await DefaultApi().shareCommentThumbPost(
          groupId: state.groupId.value,
          shareId: item.id,
          userId: currentUserId,
          isShowLoading: false,
        );
        
        if (response != null && response['code'] == 200) {
          // 重新加载互动墙以获取最新数据
          await loadInteractions();
          print('添加点赞成功');
        }
      }
    } catch (e) {
      print('点赞操作失败: $e');
      Toast.show('操作失败');
    }
  }

  /// 评论
  void commentInteraction(int index) {
    final item = state.interactionList[index];
    final shareId = item.id;
    
    // 显示评论输入框 - 使用中间弹窗
    Get.dialog(
      _CommentDialog(
        onSubmit: (content) {
          createComment(shareId, content);
        },
      ),
    );
  }

  /// 创建评论
  Future<void> createComment(int shareId, String content) async {
    try {
      final currentUserId = AuthController.to.user?.userId;
      
      final response = await DefaultApi().shareCreateCommentPost(
        groupId: state.groupId.value,
        shareId: shareId,
        userId: currentUserId!,
        content: content,
        isShowLoading: true,
      );
      
      if (response != null && response['code'] == 200) {
        Toast.show('评论成功');
        // 重新加载互动墙
        await loadInteractions();
      }
    } catch (e) {
      print('评论失败: $e');
      Toast.show('评论失败');
    }
  }

  /// 删除评论
  Future<void> deleteComment(int commentId) async {
    try {
      final response = await DefaultApi().shareDeleteCommentDel(
        commentId: commentId,
        isShowLoading: true,
      );
      
      if (response != null && response['code'] == 200) {
        Toast.show('删除成功');
        // 重新加载互动墙
        await loadInteractions();
      }
    } catch (e) {
      print('删除评论失败: $e');
      Toast.show('删除失败');
    }
  }

  /// 切换卡片展开/折叠
  void toggleCardExpansion(int index) {
    if (state.expandedCards.contains(index)) {
      state.expandedCards.remove(index);
    } else {
      state.expandedCards.add(index);
    }
  }

  /// 显示操作菜单
  void showActionMenu(int index) {
    Get.bottomSheet(
      Container(
        decoration: BoxDecoration(
          color: const Color(0xFF1C1C1E),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.r),
            topRight: Radius.circular(20.r),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.delete_outline, color: Colors.red),
              title: const Text('删除', style: TextStyle(color: Colors.red)),
              onTap: () {
                Get.back();
                deleteInteraction(index);
              },
            ),
            ListTile(
              leading: Icon(Icons.cancel, color: Colors.grey[400]),
              title: Text('取消', style: TextStyle(color: Colors.grey[400])),
              onTap: () => Get.back(),
            ),
            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }

  /// 删除互动
  Future<void> deleteInteraction(int index) async {
    try {
      final item = state.interactionList[index];
      final shareId = item.id;
      
      final response = await DefaultApi().shareDeleteDel(
        shareId: shareId,
        isShowLoading: true,
      );
      
      if (response != null && response['code'] == 200) {
        Toast.show('删除成功');
        state.interactionList.removeAt(index);
      }
    } catch (e) {
      print('删除失败: $e');
      Toast.show('删除失败');
    }
  }

  /// 跳转到成员管理页
  void navigateToMemberManagement() {
    Get.toNamed('/group-member', arguments: {
      'groupId': state.groupId.value,
      'groupName': state.groupName.value,
      'groupCode': state.groupCode.value,
    });
  }
}


/// 评论对话框
class _CommentDialog extends StatefulWidget {
  final Function(String) onSubmit;

  const _CommentDialog({required this.onSubmit});

  @override
  State<_CommentDialog> createState() => _CommentDialogState();
}

class _CommentDialogState extends State<_CommentDialog> {
  late final TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xFF1C1C1E),
          borderRadius: BorderRadius.circular(16.r),
        ),
        padding: EdgeInsets.all(20.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Text(
              '评论',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 16.h),
            // 输入框
            Container(
              decoration: BoxDecoration(
                color: const Color(0xFF2C2C2E),
                borderRadius: BorderRadius.circular(12.r),
              ),
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
              child: TextField(
                controller: _controller,
                autofocus: true,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                ),
                decoration: InputDecoration(
                  hintText: '输入评论内容...',
                  hintStyle: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14.sp,
                  ),
                  border: InputBorder.none,
                  isDense: true,
                ),
                maxLines: 4,
                minLines: 3,
              ),
            ),
            SizedBox(height: 20.h),
            // 按钮
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => Get.back(),
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        color: const Color(0xFF2C2C2E),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Text(
                        '取消',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 15.sp,
                          color: Colors.grey[400],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      final content = _controller.text.trim();
                      if (content.isNotEmpty) {
                        Get.back();
                        widget.onSubmit(content);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        color: const Color(0xffF67F41),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Text(
                        '发送',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 15.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
